﻿namespace Pub.Class
{
    using System;
    using System.Collections;
    using System.Diagnostics;
    using System.Reflection;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Threading;
    using System.Web;
    using System.Xml;

    public class Safe
    {
        private static void _expandException(Exception ex, int offSet, StringBuilder sb)
        {
            if (!ex.IsNull())
            {
                Type type = ex.GetType();
                string str = "";
                if (offSet > 1)
                {
                    str = new string(' ', offSet * 4);
                }
                sb.AppendFormat("{0}Exception:   {1}{2}", str, type.Name, Environment.NewLine);
                sb.AppendFormat("{0}Message:     {1}{2}", str, ex.Message, Environment.NewLine);
                sb.AppendFormat("{0}Source:      {1}{2}", str, ex.Source, Environment.NewLine);
                if (ex.StackTrace.IsNotNull())
                {
                    sb.AppendFormat("{0}Stack Trace: {1}{2}", str, ex.StackTrace.Trim(), Environment.NewLine);
                }
                if (ex.TargetSite.IsNotNull())
                {
                    sb.AppendFormat("{0}Method:      {1}{2}", str, ex.TargetSite.Name, Environment.NewLine);
                }
                sb.AppendFormat("{0}Native:      {1}{2}", str, ex.ToString(), Environment.NewLine);
                sb.AppendFormat("{0}Data:        {1}{2}", str, expandData(ex.Data, offSet), Environment.NewLine);
                _expandException(ex.InnerException, offSet + 1, sb);
            }
        }

        public static object DllInvoke(string DllFileName, string NameSpace, string ClassName, string MethodName, object[] ObjArrayParams)
        {
            foreach (Type type in Assembly.LoadFrom(DllFileName).GetTypes())
            {
                if ((type.Namespace == NameSpace) && (type.Name == ClassName))
                {
                    MethodInfo method = type.GetMethod(MethodName);
                    if (method.IsNotNull())
                    {
                        object obj2 = Activator.CreateInstance(type);
                        return method.Invoke(obj2, ObjArrayParams);
                    }
                }
            }
            return 0;
        }

        public static string Expand(Exception ex)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("*******************************************************************************************************");
            if (!HttpContext.Current.IsNull())
            {
                sb.AppendLine(string.Format("* DateTime :   {0}\tIP：{1}\tMemberID：{2}\tOS：{3}\tBrower：{4}", new object[] { DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Request2.GetIP(), "", Request2.GetOS(), Request2.GetBrowser() }));
                sb.AppendLine("* Url      :   " + Request2.GetUrl());
                sb.AppendLine("* Request  :   " + Request2.GetRequest());
            }
            _expandException(ex, 1, sb);
            sb.AppendLine("*******************************************************************************************************");
            sb.AppendLine("");
            return sb.ToString();
        }

        private static string expandData(IDictionary iDictionary, int offSet)
        {
            StringBuilder builder = new StringBuilder();
            offSet += 4;
            string str = "";
            if (offSet > 1)
            {
                str = new string(' ', offSet);
            }
            builder.AppendFormat("{0}Total Data Entries: {1}{2}", str, iDictionary.Count, Environment.NewLine);
            int num = 1;
            str = new string(' ', str.Length + 4);
            foreach (DictionaryEntry entry in iDictionary)
            {
                builder.AppendFormat("{0}{1}:[{2} {3}]  ", new object[] { str, num++, entry.Key.GetType().FullName, entry.Key.ToString() });
                if (entry.Value.IsNotNull())
                {
                    builder.AppendFormat("{0}", entry.Value.ToString());
                }
                else
                {
                    builder.AppendFormat("{0}", "(null)");
                }
                builder.Append(Environment.NewLine);
            }
            return builder.ToString();
        }

        public static int IsExistProcess(string processName)
        {
            int num = 0;
            Process[] processesByName = Process.GetProcessesByName(processName);
            for (int i = 0; i < processesByName.Length; i++)
            {
                Process process1 = processesByName[i];
                num++;
            }
            return num;
        }

        public static bool IsRefresh(int seconds)
        {
            string input = Cookie2.Get("__sysTime");
            if (input.Trim() != "")
            {
                if (!input.IsDateTime())
                {
                    return true;
                }
                DateTime startTime = DateTime.Parse(input);
                DateTime now = DateTime.Now;
                if (startTime.GetTimeSpan(now).Seconds >= seconds)
                {
                    return false;
                }
                Js.Alert("不允许刷新，或快速提交数据，请" + seconds.ToString() + "秒后提交数据。");
            }
            return true;
        }

        public static bool IsSafeUrl(string doMain)
        {
            string str = Request2.GetReferrer().ToLower().Trim().Replace("http://", "").Replace("https://", "").Split(new char[] { '/' })[0];
            doMain = doMain.ToLower().Trim();
            return (str.IndexOf(doMain) > -1);
        }

        public static void KillProcess(string processName)
        {
            if (string.IsNullOrEmpty(processName))
            {
                throw new ArgumentNullException("ProcessName");
            }
            KillProcessAsync(processName, 0);
        }

        public static void KillProcess(string processName, int TimeToKill)
        {
            if (string.IsNullOrEmpty(processName))
            {
                throw new ArgumentNullException("ProcessName");
            }
            ThreadPool.QueueUserWorkItem(param0 => KillProcessAsync(processName, TimeToKill));
        }

        public static void KillProcessAsync(string processName, int TimeToKill)
        {
            if (TimeToKill > 0)
            {
                Thread.Sleep(TimeToKill);
            }
            foreach (Process process in Process.GetProcessesByName(processName))
            {
                process.Kill();
            }
        }

        public static void RestartIISProcess()
        {
            try
            {
                XmlDocument document = new XmlDocument();
                document.Load("~/web.config".GetMapPath());
                XmlTextWriter w = new XmlTextWriter("~/web.config".GetMapPath(), null) {
                    Formatting = Formatting.Indented
                };
                document.WriteTo(w);
                w.Flush();
                w.Close();
            }
            catch
            {
            }
        }

        public static string RunAsync(string cmd, string arguments = "")
        {
            string str;
            cmd = "\"" + cmd + "\"";
            using (Process process = new Process())
            {
                process.StartInfo.FileName = cmd;
                if (!arguments.IsNullEmpty())
                {
                    process.StartInfo.Arguments = arguments;
                }
                process.StartInfo.UseShellExecute = false;
                try
                {
                    process.Start();
                    process.PriorityClass = ProcessPriorityClass.High;
                    process.Close();
                    str = string.Empty;
                }
                catch (Exception exception)
                {
                    str = exception.ToExceptionDetail();
                }
            }
            return str;
        }

        public static string RunAsync(string cmd, ProcessWindowStyle winStyle, string arguments = "")
        {
            string str;
            cmd = "\"" + cmd + "\"";
            using (Process process = new Process())
            {
                process.StartInfo.FileName = cmd;
                if (!arguments.IsNullEmpty())
                {
                    process.StartInfo.Arguments = arguments;
                }
                process.StartInfo.WindowStyle = winStyle;
                process.StartInfo.UseShellExecute = true;
                try
                {
                    process.Start();
                    process.PriorityClass = ProcessPriorityClass.High;
                    process.Close();
                    str = string.Empty;
                }
                catch (Exception exception)
                {
                    str = exception.ToExceptionDetail();
                }
            }
            return str;
        }

        public static string RunWait(string cmd, ProcessWindowStyle winStyle, string arguments = "")
        {
            string str;
            cmd = "\"" + cmd + "\"";
            using (Process process = new Process())
            {
                process.StartInfo.FileName = cmd;
                process.StartInfo.Arguments = arguments;
                process.StartInfo.WindowStyle = winStyle;
                process.StartInfo.UseShellExecute = true;
                try
                {
                    process.Start();
                    process.PriorityClass = ProcessPriorityClass.High;
                    process.WaitForExit();
                    process.Close();
                    str = string.Empty;
                }
                catch (Exception exception)
                {
                    str = exception.ToExceptionDetail();
                }
            }
            return str;
        }

        public static string RunWait(string cmd, string arguments = "", bool isOutput = false, string[] commands = null)
        {
            string str3;
            cmd = "\"" + cmd + "\"";
            using (Process process = new Process())
            {
                process.StartInfo.FileName = cmd;
                process.StartInfo.Arguments = arguments;
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardInput = true;
                process.StartInfo.RedirectStandardOutput = isOutput;
                process.StartInfo.RedirectStandardError = true;
                process.StartInfo.CreateNoWindow = true;
                try
                {
                    process.Start();
                    if (commands.IsNotNull())
                    {
                        foreach (string str in commands)
                        {
                            process.StandardInput.WriteLine(str);
                        }
                    }
                    process.PriorityClass = ProcessPriorityClass.High;
                    string str2 = process.StandardError.ReadToEnd().Trim();
                    if (isOutput)
                    {
                        str2 = str2 + " " + process.StandardOutput.ReadToEnd().Trim();
                    }
                    process.WaitForExit();
                    process.Close();
                    str3 = str2.Trim();
                }
                catch (Exception exception)
                {
                    str3 = exception.ToExceptionDetail();
                }
            }
            return str3;
        }

        public static void SafeGetPost(string doMain)
        {
            if (!string.IsNullOrEmpty(doMain))
            {
                bool flag = false;
                string[] strArray = doMain.Split(new char[] { '|' });
                for (int i = 0; i <= (strArray.Length - 1); i++)
                {
                    if (IsSafeUrl(strArray[i]))
                    {
                        flag = true;
                    }
                }
                if (!flag)
                {
                    Msg.Write("不允许在本地提交数据。");
                    Msg.End();
                }
            }
        }

        public static void SetDateTime()
        {
            Cookie2.Set("__sysTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        }
    }
}

